package com.example.day19_7_19_1.model;

import com.example.day19_7_19_1.base.BaseModel;
import com.example.day19_7_19_1.bean.ItemBean;
import com.example.day19_7_19_1.bean.TabBean;
import com.example.day19_7_19_1.net.ApiService;
import com.example.day19_7_19_1.util.HttpUtil;
import com.example.day19_7_19_1.util.LogUtil;
import com.example.day19_7_19_1.util.ResultBack;

import java.util.HashMap;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.ResourceSubscriber;

public class IModel extends BaseModel {
    public void getData(int id, final ResultBack<ItemBean> resultBack) {
        HttpUtil.getInstance().getApiService(ApiService.itemUrl)
                .getData(id)
                .compose(IModel.<ItemBean>rxSchedulerHelper())
                .subscribe(new ResultSubscriber<ItemBean>() {
                    @Override
                    public void onNext(ItemBean itemBean) {
                        resultBack.succeed(itemBean);
                    }
                });
    }

    public void getTabData(final ResultBack<TabBean> resultBack){
        HttpUtil.getInstance().getApiService(ApiService.tabUrl)
                .getTabData()
                .compose(IModel.<TabBean>rxSchedulerHelper())
                .subscribe(new ResultSubscriber<TabBean>() {
                    @Override
                    public void onNext(TabBean tabBean) {
                        resultBack.succeed(tabBean);
                    }
                });
    }

    //切换线程
    public static <T> FlowableTransformer<T,T> rxSchedulerHelper(){
        //compose简化线程
        return new FlowableTransformer<T, T>() {
            @Override
            public Flowable<T> apply(Flowable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())//被观察者执行的线程
                        .observeOn(AndroidSchedulers.mainThread());//观察者执行的线程
            }
        };
    }
    //错误处理
    public abstract class ResultSubscriber<T> extends ResourceSubscriber<T>{
        @Override
        public void onError(Throwable t) {
            LogUtil.logd(t.getMessage());
        }

        @Override
        public void onComplete() {

        }
    }
}
